<?php
declare (strict_types = 1);

namespace app\service\logic\api\site;

use app\exception\AuthException;
use app\exception\LogicException;
use app\model\communal\UserExpertModel;
use app\model\communal\UserModel;
use app\service\logic\common\user\InviteService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;

final class SiteService
{
    /**
     * 删除验证码缓存
     *
     * @param $params
     * @return bool
     */
    public function removeCaptcha($params)
    {
        $mobile = $params['mobile'];
        $cacheKey = 'sms_' . $mobile;
        return Cache::delete($cacheKey);
    }

    /**
     * 用户登录
     *
     * @param $params
     * @return array
     * @throws AuthException
     */
    public function userLogin($params)
    {
        $user = UserModel::where('mobile', $params['mobile'])->findOrEmpty();
        if ($user->isEmpty()) {
            // 创建用户
            $params['name'] = '昵称' . substr($params['mobile'], -4);
            Db::connect('communal')->transaction(function () use ($params, &$user) {
                $user = UserModel::create($params, ['name', 'mobile']);
                // 是否存在邀请
                if (isset($params['from']) && !empty($params['from'])) {
                    invoke(InviteService::class)->invite($params['from'], $user['id']);
                }
            });
        } else {
            if (!$user->validateState()) {
                throw new AuthException(lang('communal.account state disable'));
            }
        }

        $token = auth('user')->login($user);
        return [
            'user' => $user,
            'token' => $token
        ];
    }

    /**
     * 庄家登录
     *
     * @param $params
     * @return array
     * @throws AuthException
     * @throws LogicException
     */
    public function expertLogin($params)
    {
        $user = UserExpertModel::where('mobile', $params['mobile'])->findOrEmpty();

        if ($user->isEmpty()) {
            throw new LogicException(lang('communal.mobile not found'));
        }

        if (!$user->validateState()) {
            throw new AuthException(lang('communal.account state disable'));
        }

        $token = auth('expert')->login($user);
        return [
            'user' => $user,
            'token' => $token
        ];
    }

    /**
     * 修改密码
     *
     * @param $params
     * @return bool
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    // public function password($params)
    // {
    //     $adminModel = AdminModel::where('mobile', $params['mobile'])->findOrFail();
    //     $params['password'] = HasherFacade::make($params['password']);
    //     $result = $adminModel->allowField(['password'])->save($params);
    //
    //     // 禁用
    //     event('AfterPassword', ['id' => $adminModel['id']]); // 可队列
    //     return $result;
    // }
}
